package com.asen.commons.core.listener;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 服务操作处理
 *
 * @author Gary
 * @version 1.0
 * @date 2019-12-05
 */
//@Component
//@Aspect
//@Slf4j
//@Order(-1)
public class ServiceActionAspect {

    private ServiceActionHolder serviceActionHolder;

    @Pointcut(value = "@annotation(com.asen.commons.annotation.ActionMethod)")
    public void pointcutMethod() {

    }

    @Around("pointcutMethod()")
    public Object aroundCon(ProceedingJoinPoint point) throws Throwable {
        Signature signature = point.getSignature();

        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("注解[com.abel.annotation.ActionMethod]只能用于方法！");
        }

        ServiceContext serviceContext = null;
        List<ServiceActionListener> listeners = serviceActionHolder.getListeners(point.getTarget().getClass());
        MethodSignature methodSignature = (MethodSignature) signature;
        if (listeners.size() > 0) {
            Object target = point.getTarget();
            // 先简单处理method方法
//            Method method = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
            Method method = methodSignature.getMethod();
            serviceContext = new ServiceContext();
//            serviceContext.setMethod(method);
//            serviceContext.setTarget(target);
//            serviceContext.setArgs(point.getArgs());
            for (ServiceActionListener listener : listeners) {
                listener.before(serviceContext);
            }
        }

        Object object = point.proceed();

        if (listeners.size() > 0) {
            serviceContext.setResult(object);
            for (ServiceActionListener listener : listeners) {
                listener.after(serviceContext);
            }
            object = serviceContext.getResult();
        }

        return object;
    }
}
